﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using suanpan.API.Components.Core;
using suanpan.API.Components.OAuth;
using suanpan.API.Components.Behaviors.ErrorHandling;
using suanpan.API.Components.Exceptions;
using suanpan.API.Components.Channels.Core;

namespace suanpan.API.Components.Channels.OAuth
{
    class OAuthChannel : RestChessChannel
    {
        #region Properties

        protected OAuthContext Context { get; set; }

        #endregion

        #region CTor


        public OAuthChannel(ChannelManagerBase manager, IReplyChannel innerChannel)
            : base(manager, innerChannel) { }

        #endregion

        #region Overriden Methods
        
        override protected void OnReceive(ref Message message)
        {
            try
            {
                this.Context = new OAuthContext(message);
                string exceptionMessage;

                OAuthManager oAuth = new OAuthManager();
                if (!oAuth.IsAuthenticated(this.Context, out exceptionMessage))
                {
                    RestErrorMessage errorMessage = new RestErrorMessage(new DigitalSignatureException(exceptionMessage));
                    this.SendErrorMessage(ref message, errorMessage);
                    return;
                }
            }
            catch (RESTException rex)
            {
                RestErrorMessage errorMessage = new RestErrorMessage(rex);
                this.SendErrorMessage(ref message, errorMessage);
            }
            catch (System.Exception ex)
            {
                RestErrorMessage errorMessage = new RestErrorMessage(new AuthenticationException(ex));
                this.SendErrorMessage(ref message, errorMessage);
            }  
        }
        override protected void OnSend(ref Message message)
        {
            
        }

        #endregion
    }
}
